package com.sjp.demo.rpc.provider;

import com.sjp.demo.rpc.model.RpcRequest;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Map;

public class ProcessorHandler implements Runnable {
    private Socket socket;
    private Map<String, Object> serviceMap;

    public ProcessorHandler(Socket socket, Map<String, Object> serviceMap) {
        this.serviceMap = serviceMap;
        this.socket = socket;
    }

    @Override
    public void run() {
        try (
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream())
        ) {

            RpcRequest rpcRequest = (RpcRequest) objectInputStream.readObject();
            System.out.println("处理请求：" + rpcRequest);
            Object result = invoke(rpcRequest);
            System.out.println("处理结果：" + result);
            objectOutputStream.writeObject(result);
            objectOutputStream.flush();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Object invoke(RpcRequest request) throws Exception {
        Object service = serviceMap.get(request.getServiceName());
        if (service == null) {
            throw new RuntimeException("service不存在");
        }
        Object[] params = request.getParams();
        Class<?>[] types = new Class[params.length];
        for (int i = 0; i < params.length; i++) {
            types[i] = params[i].getClass();
        }
        Class<?> clazz = service.getClass();
        Method method = clazz.getMethod(request.getMethodName(), types);

        return method.invoke(service, params);

    }

}
